setwd("E://OneDrive//1-教学//科技论文写作//课件//课上使用的文档//2.9.5-科研绘图//箱型图")

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ToothGrowth

library(ggplot2)

ggplot(ToothGrowth)+ 
  geom_boxplot(aes(x = dose, y = len))


ggplot(ToothGrowth)+ 
  geom_boxplot(aes(x = dose, y = len))+
  coord_flip()    #转置


ggplot(ToothGrowth)+ 
  geom_boxplot(aes(x = dose, y = len), notch=TRUE) #缺口


ggplot(ToothGrowth)+ 
  geom_boxplot(aes(x = dose, y = len))+
  stat_summary(aes(x = dose, y = len), fun.y = mean, 
               geom = "point", shape = 23, size = 4)#添加平均值点


ggplot(ToothGrowth)+ 
  geom_boxplot(aes(x = dose, y = len, fill = supp))+
  stat_summary(aes(x = dose, y = len, fill = supp), 
               fun.y = mean, geom = "point", shape = 23, size = 4, position = position_dodge(0.75))#分组


#绘制箱型图两两比较
install.packages("ggsignif") 
library(ggsignif)

ggplot(ToothGrowth)+ 
  geom_boxplot(aes(x = dose, y = len))+
  stat_summary(aes(x = dose, y = len), 
               fun.y = mean, geom = "point", shape = 23, size = 4)+
  geom_signif(aes(x = dose, y = len), 
              comparisons = list(c("0.5","1"), c("0.5","2"), c("1","2")),
              map_signif_level = F,
              textsize = 5,
              test = t.test,    #t检验
              step_increase = 0.2,
              size = 1,
              test.args = c("less")) + #可选显示参数为：two.sided, greater, less)
  scale_y_continuous(limits = c(3, 50))+ #调整y坐标范围，保证全部显示
  theme_classic()


#小提琴图
ggplot(ToothGrowth)+
  geom_violin(aes(x = dose, y = len, fill = supp))

ggplot(ToothGrowth)+
  geom_violin(aes(x = dose, y = len, fill = supp), position = position_dodge(0.75))+
  geom_boxplot(aes(x = dose, y = len, fill = supp), 
               width = 0.1, position = position_dodge(0.75))+
  stat_summary(aes(x = dose, y = len, fill = supp), 
               fun.y = mean, geom = "point", shape = 23, size = 4, position = position_dodge(0.75))+
  theme_bw()
